import pck from "../../package.json";
/**
 * 此文件谷歌存储相关任务数据
 * @author rammo
 * @license MIT
 */

// 保存标题
export const saveTitleLocalstory = (title) => {
  if (chrome.storage) {
    chrome.storage.sync.set({ title: title }, () => {
      console.log("😄 Save Title Success～");
    });
  } else {
    localStorage.setItem(`${pck.name}-title`, title);
    console.log("😄 Save Title Success～");
  }
};

// 获取标题
export const getTitleLocalstory = (setTasks) => {
  if (chrome.storage) {
    chrome.storage.sync.get("title", (result) => {
      setTasks(result?.title || "");
      console.log("👌 Get Title Success～");
    });
  } else {
    const title = localStorage.getItem(`${pck.name}-title`);
    setTasks(title || "");
    console.log("👌 Get Title Success～");
  }
};

// 保存任务
export const saveTasksListLocalstory = (tasks) => {
  if (chrome.storage) {
    chrome.storage.sync.set({ tasks: tasks }, () => {
      console.log(tasks, "334");
      console.log("😄 🚀  Create and Update Tasks Success～");
    });
  } else {
    localStorage.setItem(`${pck.name}-tasks`, JSON.stringify(tasks));
    console.log("😄 🚀  Create and Update Tasks Success～");
  }
};

// 获取任务
export const getTasksListLocalstory = (setTasks) => {
  if (chrome.storage) {
    chrome.storage.sync.get("tasks", (result) => {
      setTasks(result?.tasks || []);
      console.log(result, "234");
      console.log("👌 Get Tasks Success～");
    });
  } else {
    const tasks = JSON.parse(localStorage.getItem(`${pck.name}-tasks`));
    setTasks(tasks || []);
    console.log("👌 Get Tasks Success～");
  }
};

// 清除任务
export const clearTasksLocalstory = () => {
  if (chrome.storage) {
    chrome.storage.sync.remove("tasks", () => {
      console.log("🧹 Clear Tasks Success～");
    });
  } else {
    localStorage.removeItem(`${pck.name}-tasks`);
    console.log("🧹 Clear Tasks Success～");
  }
};

// 任务个数
export const setBadegeText = (text = "0", bgColor) => {
  if (chrome.storage) {
    chrome.action.setBadgeText({ text });
    chrome.storage.sync.get("bgColor", (result) => {
      const color = bgColor || result.bgColor || "#4ea30a";
      chrome.action.setBadgeBackgroundColor({ color });
    });
  }
};
